package com.example.demo.controller;

import com.example.demo.config.AjaxResult;
import com.example.demo.model.ExpressInfo;
import com.example.demo.model.OrderInfo;
import com.example.demo.model.UserInfo;
import com.example.demo.service.ExpressService;
import com.example.demo.util.ConstVariable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.demo.service.SellerOrderService;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/seller/order")
public class SellerOrderController {
    private static final Logger log = LoggerFactory.getLogger(SellerOrderController.class);

    @Autowired
    private SellerOrderService sellerOrderService;

    @Autowired
    private ExpressService expressService;

    @GetMapping("/list")
    public AjaxResult getSoldOrders(@RequestParam(required = false) String status, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            List<OrderInfo> orders = sellerOrderService.getSoldOrders(userInfo.getId(), status);
            return AjaxResult.success(orders);
        } catch (Exception e) {
            log.error("获取卖出的订单失败", e);
            return AjaxResult.fail("获取订单失败");
        }
    }

    @GetMapping("/listComment")
    public AjaxResult getSoldOrdersComment(HttpSession session, String status) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            List<OrderInfo> orders = sellerOrderService.getSoldOrdersComment(userInfo.getId(), status);
            return AjaxResult.success(orders);
        } catch (Exception e) {
            log.error("获取卖出的订单失败", e);
            return AjaxResult.fail("获取订单失败");
        }
    }

    @PostMapping("/cancel")
    public AjaxResult cancelOrder(@RequestParam String orderNo, 
                                @RequestParam(required = false) String reason,
                                HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            int success = sellerOrderService.cancelOrder(orderNo, userInfo.getId(), reason);
            return success > 0 ? AjaxResult.success("取消订单成功") : AjaxResult.fail("取消订单失败");
        } catch (Exception e) {
            log.error("取消订单失败", e);
            return AjaxResult.fail("取消订单失败");
        }
    }

    @GetMapping("/cancel-reason/{orderNo}")
    public AjaxResult getCancelReason(@PathVariable String orderNo, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            String reason = sellerOrderService.getCancelReason(orderNo, userInfo.getId());
            return AjaxResult.success(Map.of("reason", reason));
        } catch (Exception e) {
            log.error("获取取消原因失败", e);
            return AjaxResult.fail("获取取消原因失败");
        }
    }

    @GetMapping("/detail/{orderNo}")
    public AjaxResult getOrderDetail(@PathVariable String orderNo, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            OrderInfo orderDetail = sellerOrderService.getOrderDetail(orderNo, userInfo.getId());
            if (orderDetail == null) {
                return AjaxResult.fail("订单不存在或无权查看");
            }
            return AjaxResult.success(orderDetail);
        } catch (Exception e) {
            log.error("获取订单详情失败", e);
            return AjaxResult.fail("获取订单详情失败");
        }
    }

    @PostMapping("/ship")
    public AjaxResult ship(@RequestBody Map<String, String> params, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }

            String orderNo = params.get("orderNo");
            String expressNo = params.get("expressNo");
            String companyName = params.get("companyName");
            String senderName = params.get("senderName");
            String senderPhone = params.get("senderPhone");
            String senderAddress = params.get("senderAddress");
            String receiverAddress = params.get("receiverAddress");
            
            // 验证必填字段
            if (orderNo == null || expressNo == null || companyName == null || 
                senderName == null || senderPhone == null || senderAddress == null) {
                return AjaxResult.fail("请填写完整的发货信息");
            }

            // 验证手机号格式
            if (!senderPhone.matches("^1[3-9]\\d{9}$")) {
                return AjaxResult.fail("请输入正确的手机号码");
            }

            ExpressInfo expressInfo = new ExpressInfo();
            expressInfo.setOrderNo(orderNo);
            expressInfo.setExpressNo(expressNo);
            expressInfo.setCompanyName(companyName);
            expressInfo.setSenderName(senderName);
            expressInfo.setSenderPhone(senderPhone);
            expressInfo.setSenderAddress(senderAddress);
            expressInfo.setReceiverAddress(receiverAddress);
            expressInfo.setSendTime(new Date());
            
            boolean success = sellerOrderService.ship(expressInfo, userInfo.getId());
            return success ? AjaxResult.success("发货成功") : AjaxResult.fail("发货失败");
        } catch (Exception e) {
            log.error("发货失败", e);
            return AjaxResult.fail("发货失败: " + e.getMessage());
        }
    }

    @PostMapping("/delete")
    public AjaxResult deleteOrder(@RequestParam String orderNo, HttpSession session) {
        System.err.println("orderNo: " + orderNo);
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            boolean success = sellerOrderService.deleteOrder(orderNo, userInfo.getId());
            return success ? AjaxResult.success("删除成功") : AjaxResult.fail("删除失败");
        } catch (Exception e) {
            log.error("删除订单失败", e);
            return AjaxResult.fail("删除订单失败");
        }
    }

    @GetMapping("/count")
    public AjaxResult getOrderCount(HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }
            
            Map<String, Integer> counts = sellerOrderService.getOrderCount(userInfo.getId());
            return AjaxResult.success(counts);
        } catch (Exception e) {
            log.error("获取订单统计失败", e);
            return AjaxResult.fail("获取订单统计失败");
        }
    }

    @PostMapping("/remark")
    public AjaxResult updateRemark(@RequestBody Map<String, String> params, HttpSession session) {
        try {
            UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
            if (userInfo == null) {
                return AjaxResult.fail("请先登录");
            }

            String orderNo = params.get("orderNo");
            String remark = params.get("remark");
            
            if (orderNo == null) {
                return AjaxResult.fail("订单号不能为空");
            }

            boolean success = sellerOrderService.updateRemark(orderNo, remark, userInfo.getId());
            return success ? AjaxResult.success("更新备注成功") : AjaxResult.fail("更新备注失败");
        } catch (Exception e) {
            log.error("更新订单备注失败", e);
            return AjaxResult.fail("更新订单备注失败");
        }
    }

    @GetMapping("/express/{orderNo}")
    public AjaxResult getExpress(@PathVariable String orderNo, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute(ConstVariable.USER_SESSION_KEY);
        if (userInfo == null) {
            return AjaxResult.fail("请先登录");
        }
        return AjaxResult.success(expressService.getByOrderNo(orderNo));
    }
} 